---
title: "Cleaning Religion and State Dataset"
---

# Load

```{r}
# load packages
  source("helper-packages.R")

# load data
  ras_raw <- 
    import("../raw-data/x-relig-and-state/The Religion and State Project, Main Dataset and Societal Module, Round 3.DTA")
```

# Clean

```{r}
# clean
  ras_clean <- 
    ras_raw %>% 
    select(
      country,
      starts_with("MXX"),
      starts_with("WSOCDISX"),
      -c(ends_with("X"))) %>% 
    pivot_longer(
      cols = -country,
      names_pattern = "(MXX|WSOCDISX)(.*)",
               names_to = c(".value", "year")) %>% 
    mutate(across(year, ~as.numeric(.))) %>% 
    mutate(
      country = ifelse(country == "Serbia (Yugoslavia)" & year < 1992, "Yugoslavia", country),
      country = ifelse(country == "Serbia (Yugoslavia)" & year >= 1992, "Serbia", country),
      country = ifelse(country == "Venezuala", "Venezuela", country),
      country1 = countryname(country))

# add year rows for each country
  ras_clean_rows_added <- 
    ras_clean %>% 
    group_by(country) %>% 
      do(add_row(., year = c(2015:2020), .after = 6)) %>%
    ungroup() %>% 
    fill(country) %>%
    group_by(country) %>%
    arrange(country, year) %>%
    mutate(temp_WSOCDISX_inter = (lag(WSOCDISX, 1) + lag(WSOCDISX, 2) + lag(WSOCDISX, 3))/3) %>% 
    group_by(country) %>% 
    fill(temp_WSOCDISX_inter) %>%
    mutate(
      WSOCDISX_inter =
        case_when(
          year %in% c(1990:2014) ~ WSOCDISX,
          TRUE ~ temp_WSOCDISX_inter)) %>%
    select(-c("temp_WSOCDISX_inter")) %>%
    mutate(ras_country_common = countryname(country)) %>%
    filter(!country %in% c("Kurdistan (Iraq)", "Cyprus, Turkish", "Gaza")) %>% # keep main parts of divided states
    select(
      ras_country_common,
      ras_year = year,
      ras_social_disc = WSOCDISX_inter) %>% 
    na.omit() %>%
    mutate(
      ras_social_disc_15_and_above = 
        (ras_social_disc >= 15)*1) 
```

# Save data

```{r}
  saveRDS(ras_clean_rows_added, "../cleaned-data/x-5-relig-and-state.rds")
```
